import global from './global'
import mApi from "@/utils/mapi";
import { showLoading, hideLoading } from '@/utils/helper';
import { memberCompany,getStoreList,queryDistance,getMemberInfo,queryMemberInfo} from '@/api/vmeitime-http/index.js'
// import { storeToRefs } from 'pinia';
import { useShopStore } from '@/stores/shopStore';
import { useUserStore } from '@/stores/commonStore';
import { useCartStore } from '@/stores/cartStore';
const shopStore = useShopStore();
const userStore = useUserStore();
const cartStore = useCartStore();
// const { sellerMemberId, shopInfo, changeShopType, isFirstVisit } = storeToRefs(store)
import { getSaveShare } from '@/api/vmeitime-http/index.js'
 //保存分享参数
export function takeSaveShare(paramData) {
	const sysinfo = uni.getStorageSync('sysinfo') || {};
	return new Promise(async (resolve, reject) => {
		let dparam = {
			event_id: '', //事件id  1:会员注册, 2:H5分享， 3:商品价格标签, 4:商品超链接分享, 5:拼团， 6:线下团购,7.总部推广 ,8.VIP专属卡,9.预留1,10.预留2
			source_type: '', //1首页分享，2商品分享，3名片分享，4商品超链接分享5拼团,6线下团购,7.总部推广 ,8.VIP专属卡,9.预留1,10.预留2
			goods_id: '',
			goods_sku: '',
			activity_id: '',
			system_id: 'S039',
			// buy_member_id: paramData.buy_member_id || '', //用户id
			sell_member_id: '', //门店id
			phone_model: transTsring(sysinfo.model || '') , //手机型号(优先前端)
			wechat_version: transTsring(sysinfo.version || ''), //微信版本号
			use_system: transTsring(sysinfo.system || ''), //客户端手机操作系统及版本号
		}
		let ndata = Object.assign(dparam, paramData)
		getSaveShare({ request_params: JSON.stringify(ndata) })
			.then(res => {
				console.log('获取方法[getSaveShare]分享id', JSON.stringify(res));
				if (res.result && res.object) {
					let nres = res.object || {};
					resolve(nres.share_id || '');

				} else {
					resolve('')
					uni.showToast({
						mask: true,
						title: res.shortMessage || '分享保存失败！',
						icon: 'none'
					});
					return;
				}
			})
			.catch(err => {
				reject(err)
				console.log('分享getSaveShare保存失败:', err);
			});
	})
}
// 过滤特殊字符
export function transTsring(v:any){
	let r = '';
	if(v){
		r = v.replace(/[^\u4e00-\u9fa5a-zA-Z0-9\s.,!?，。？！]+/g, '');
	}
	console.log('transTsring',r)
	return r
}
// 获取卖家配置信息
export function getSellerConfig() {
	return new Promise(async (resolve, reject) => {
		//[{id: '1130',name: '堂食'},{id: '1120',name: '自取'},{id: '1131',name: '外卖'}]
		let dfarr = [{id: '1131',name: '外卖'}],fid = '1131',r={list:dfarr,fid:fid,sfitem:{ id: '1131', name: '外卖' }};
		try {
			let res = await getMemberInfo({ memberId: shopStore.curSellerMemberId })
			if (!res.result||!res.object) {
				shopStore.setShopConfig({});
				resolve(r);
				return
			}
			let nres = res.object||{};
			const scopeMapping = {
				"1120": { id: '1120', name: '自取' },
				"1130": { id: '1130', name: '堂食' },
				"1131": { id: '1131', name: '外卖' }
			};
			let nr = [],nsc = nres.scope||'',sfitem={ id: '1131', name: '外卖' };
			const scopeArray = nsc.split(',');
			let h = scopeArray.some(itm=>itm&&itm==shopStore.costPlan);
			fid = h?shopStore.costPlan:nres.default_scope||'1131';//初始化选中缓存/默认
			
			fid!=shopStore.costPlan?shopStore.setCostPlan(fid):'';
			if (scopeArray.includes("1130")) nr.push(scopeMapping["1130"]); // 堂食
			if (scopeArray.includes("1131")) nr.push(scopeMapping["1131"]); // 外卖
			if (scopeArray.includes("1120")) nr.push(scopeMapping["1120"]); // 自取
			//打烊v1.0(前端根据营业时间、bus_status、work_status自行判断)
			// let hasShutTime=true;//是否打烊时间
			if(nres.vstartTime&&nres.vendTime){
				let formattedTime = `${nres.vstartTime.slice(0, 2)}:${nres.vstartTime.slice(2)} - ${nres.vendTime.slice(0, 2)}:${nres.vendTime.slice(2)}`;
				shopStore.setShutTimes(formattedTime)//营业时间
				    // const now = new Date();
				    // const currentTime = now.getHours() * 100 + now.getMinutes();
				    // const startTime = parseInt(nres.vstartTime);
				    // const endTime = parseInt(nres.vendTime);
				    // hasShutTime=!(currentTime > startTime && currentTime < endTime);
			}else{
				shopStore.setShutTimes('');
			}
			// let hasShut= false;//是否显示购物车状态
			// if(hasShutTime){
			// 	hasShut=true;
			// }else{
			// 	hasShut = !((nres.bus_status == '44' && nres.work_status == '974') || nres.work_status == '233');
			// }
			// let shutStates='opens';//营业状态 44营业、45停止。974到店、973离店 （opens：打烊、stops暂停营业）
			// if (hasShutTime && nres.bus_status == '44' && nres.work_status == '974') {
			//     shutStates = 'opens';
			// } else if ((nres.bus_status == '45' && nres.work_status == '974') || 
			//            (nres.bus_status == '44' && nres.work_status == '973') ||
			//            (nres.bus_status == '45' && nres.work_status == '973')) {
			//     shutStates = 'stops';
			// }
			let cindex = nr.findIndex(item=>item.id==fid);
			cindex>=0?sfitem = nr[cindex]:'';
			//打烊v2.0(根据后端返回:5-营业中 6-暂停营业 7-已打烊 8-暂未开通)
			let hasShut=nres.is_open!='5'?true:false
			let shutStates=nres.is_open=='7'?'opens':(nres.is_open=='6' || nres.is_open=='8'?'stops':'opens')
			shopStore.setHasShut(hasShut);//是否打烊
			shopStore.setShutStates(shutStates);
			shopStore.setLiveSwitch(nres.liveSwitch=='5'?true:false)
			shopStore.setMealTime({preDeliverTime:nres.preDeliverTime,readyMealTime:nres.readyMealTime})
			shopStore.setSendDistance(nres.kilometre?Number(nres.kilometre)*1000:3000)
			shopStore.setStartDeliveryAmount(nres.startDeliveryAmount || 15)
			shopStore.setPackFee(nres.packFee||0)
			shopStore.setShowSaleNum(nres.showSaleNum=='5'?true:false)
			// after_phone
			shopStore.setShutPhone(nres.after_phone||'');
			r.list = nr;
			r.fid = fid;
			r.sfitem = sfitem;
			// r.loaded = true;
			shopStore.setShopConfig(r);//缓存配置-暂缓存订单类型（外卖/堂食/自提）
			resolve(r)
		} catch (e) {
			shopStore.setShopConfig({});
			resolve(r)
			reject(e);
		}
	});
}
// 获取卖家配置信息
export function takeUserInfo(source:any='') {
	return new Promise(async (resolve, reject) => {
		if(source=='check'&&userStore.userInfo.vphone){
			resolve(userStore.userInfo)
			return
		}
		try {
			let res = await queryMemberInfo()
			
			let nres = res.result&&res.object?(res.object||{}):{};
			nres.ctime = new Date().getTime();
			userStore.setUserInfo(nres)
			resolve(nres)
		} catch (e) {
			userStore.setUserInfo({})
			reject(e);
		}
	});
}
// export async function initShop(callback : (data : any) => void, obj : any) {
export function initShop(
	callback : (...params : any[]) => void,
	obj : any,
	...params : any[]
) : void {
	console.log('initShop', params);
	// let {showLoading} = params
	
	// let param = { param: obj.param, source: obj.source };
	
	if (obj.source == 'refresh' && !shopStore.isFirstVisit) {
		shopStore.setLocalTime(new Date().getTime())
		
		shopStore.setQrShop('')
		callback && callback(obj)
		return
	}
	console.log("initShop01：", userStore.changeAdress, userStore.getAdresGps.hasGps)
	const codeShopId = shopStore.qrsellerMemberId;
	if(userStore.changeAdress[0]&&userStore.getAdresGps.hasGps){
		getShop(userStore.getAdresGps.longitude, userStore.getAdresGps.latitude, obj, callback, codeShopId);
		return
	}
	// !shopStore.sellerMemberId && 
	if (shopStore.changeShopType != 'hand') {
		console.log("非手动选择01：", shopStore.changeShopType, shopStore.sellerMemberId)
		//非手动选择返回
		// getShopInfo(obj, callback);
		const codeShopId = shopStore.qrsellerMemberId;
		if ( codeShopId&& codeShopId == shopStore.sellerMemberId) {
			shopStore.setQrShop('')
			callback && callback(obj)
			return;
		} 
		//根据时间（2分钟）间隔开启定位获取当前最近门店判断是否需要切换-待+++!codeShopId && 
		if (!shopStore.isFirstVisit && (new Date().getTime() - shopStore.localTime< 60 * 2 *1000)&&codeShopId&& codeShopId == shopStore.sellerMemberId) {
			console.log('obj++++01', obj)
			// obj.param.sellerMemberId = shopStore.getters.currtshop.nmember_id || '1';
			// shopStore.setQrShop('')
			callback && callback(obj)
			return;
		}
		shopStore.setLocalTime(new Date().getTime())
		
		//优先取扫码入驻门店&冷启动
		userStore.getAdresGps.hasGps?getShop(userStore.getAdresGps.longitude, userStore.getAdresGps.latitude, obj, callback, codeShopId):getCurRelocateGps(obj, callback);
		return;
	}
	shopStore.setLocalTime(new Date().getTime()); //手动切换门店后，不立即提示切换最近门店
	// obj.param.sellerMemberId = shopTemp.nmember_id || '1';
	shopStore.setQrShop('')
	callback && callback(obj);
}
//重新定位GPS
export function getCurRelocateGps( obj:any = {}, fn) {
	obj.show && showLoading()
	const codeShopId = shopStore.qrsellerMemberId;
	uni.getLocation({
		//获取当前的位置坐标
		type: 'gcj02', //默认为 wgs84 返回 gps 坐标
		success: function(res) {
			console.log('定位获取经纬度', res);
			if (codeShopId) { 
				getShop(res.longitude, res.latitude, obj, fn, codeShopId);
				return;
			}
			// getShop(res.longitude, res.latitude, obj, fn,codeShopId);
			comparLastPositionDistance(res.longitude, res.latitude, obj,fn); 
			//比较上一次定位的位置到本次定位的位置的直线距离（大于500则请求最近门店数据，若与当前门店不同，直接切换）待+++
		},
		fail: function(result) {
			hideLoading()
			console.log('定位失败02', result);
			//成功调用授权窗口
			uni.getSetting({
				//获取用户的当前设置，返回值中只会出现小程序已经向用户请求过的权限
				success: function(res) {
					var statu = res.authSetting;
					if (!statu["scope.userLocation"]) {
						//如果设置中没有位置权限
						uni.showModal({
							//弹窗提示
							title: "授权获取地理位置",
							showCancel: true, //不显示取消
							confirmText: '确认授权',
							confirmColor: '#2CAD8D',
							content: "“小颐有约” 需要获取您当前位置",
							success: function(tip) {
								if (tip.confirm) {
									uni.openSetting({
										//点击确定则调其用户设置
										success: function(data) {
											if (data.authSetting["scope.userLocation"] === true) {
												//如果设置成功
												uni.showToast({
													//弹窗提示
													title: "定位授权成功",
													icon: "success",
													duration: 1000
												});
												uni.getLocation({
													type: 'gcj02',
													success(res) {
														console.log('定位获取经纬度',res);
														if (codeShopId) {
															getShop(res.longitude,res.latitude,obj,fn,codeShopId);
															return;
														}
														comparLastPositionDistance(res.longitude,res.latitude,obj,fn); 
													}
												});
											}
										}
									});
								} else if(tip.cancel){
									uni.exitMiniProgram()
								}else {
									//扫码注册则不定位
									// var qrRegisterSellMemberId = uni.getStorageSync(global.QR_REGISTER_SELL_MEMBERID) || '';
									const codeShopId = shopStore.qrsellerMemberId;
									if(codeShopId){
										memberCompany({ nsell_member_id: codeShopId })
											.then(resultCompany => {
												if (!resultCompany.result) {
													hideLoading()
													//自定义授权
													// shopStore.commit('common/IS_LOCAL_FAIL',true)
													return;
												}
												const cres = resultCompany.object ||{};
												const longitude = Number(cres.vgps.split(',')[0]) || '';
												const latitude = Number(cres.vgps.split(',')[1]) || '';
												const nmember_id = cres.nmember_id || '';
												getShop(longitude, latitude,obj,fn,nmember_id ||codeShopId,);
												return;
											}).catch(err => {
												hideLoading()
												console.log('查询memberCompany失败',err);
												//自定义授权
												// shopStore.commit('common/IS_LOCAL_FAIL',true)
											});
									}
									
								}
							}
						});
					} else {
						hideLoading()
						//自定义授权
						// shopStore.commit('common/IS_LOCAL_FAIL', true) //自定义授权
					}
				},
				fail: function() {
					hideLoading()
					wx.showToast({
						title: "调用授权定位失败",
						icon: "success",
						duration: 1000
					});
					return
				},
			});
		}
	});
}
export function comparLastPositionDistance(lo, la, obj = {}, fn) {
	let oldPosition = shopStore.oldGps;
	// uni.setStorageSync('oldLongitudeLatitude', lo + ',' + la);
	shopStore.setOldGps((lo + ',' + la))
	console.log("comparLastPositionDistance_oldPosition:" + oldPosition)
	if (!oldPosition) {
		// obj.isGPS = true
		// console.log('distancefn0', lo, la, obj, fn)
		getShop(lo, la, obj, fn);
		return;
	}
	queryDistance({
			longitude: oldPosition.split(',')[0], //选择门店经度
			latitude: oldPosition.split(',')[1], //选择门店纬度
			nowLongitude: lo, //定位经度
			nowLatitude: la //定位纬度
		})
		.then(res => {
			console.log('mainPromote查询距上次定位点的直线距离:', JSON.stringify(res));
			if (!res.result || !res.object) {
				getShop(lo, la, obj, fn);//+++
				// shopStore.commit('loading/hide', true)
				return;
			}
			// global.IS_FIRST = uni.getStorageSync(global.IS_FIRST_QueryMemberList)
			if (res.object.range > 500 || shopStore.isFirstVisit) {
				//请求最近的门店数据
				// obj.isGPS = true
				getShop(lo, la, obj, fn);
			} else {
				// obj.param.sellerMemberId = shopStore.getters.currtshop.nmember_id || '1';
				// shopStore.commit('loading/hide', true)
				shopStore.setQrShop('')
				console.log('distancefn2', fn)
				fn && fn(obj)
			}
		})
		.catch(err => {
			getShop(lo, la, obj, fn);//+++
			// shopStore.commit('loading/hide', true)
			console.log('查询距离失败', err);
		});
}
export function changeShop(fn:void, obj:any={}) { 
	getShop('113.064388', '28.208595', obj = {}, fn, obj.shopId)
}
// requestAllShop queryMemberList getStoreList
export function getShop(lo:any, la:any, obj:any = {}, fn:any, shopId:any='') { //在所有门店数据中根据分享二维码获取的门店id，for出对应的门店信息
   shopStore.setNowLocaGps({lo:lo,la:la})
	 getStoreList({
			longitude: lo,
			latitude: la,
			vtype_two_category: 0,
			vtype: '835',
			nmember_id: '',
			curPage: 1,
			sku:obj.sku||'',
			sellShopId: shopId || '', //指定门店
			vIsFirstShop: '小颐有约', //传值就只有一条数据
			pageSize: 200 //必须大于总门店数
		})
		.then(res => {
			console.log('查询所有门店', res);
			if (!res.result||!res.object) {
				uni.showToast({
					mask: true,
					title: '获取门店失败！',
					icon: 'none'
				});
				hideLoading()
				
				return;
			}
			// for (let key in res.object) {
			// 	if (shopId == res.object[key].nmember_id) {
			// 		// 切换门店
			// 		var thisShop = {};
			// 		thisShop[key] = res.object[key];
			// 		handlerShopInfo(thisShop, obj, fn);
			// 		break;
			// 	}
			// }
			handlerShopInfo(res.object||{}, obj, fn);
		})
		.catch(err => {
			uni.showToast({
				mask: true,
				title: '获取门店信息失败！',
				icon: 'none'
			});
			hideLoading()
			if(shopStore.curSellerMemberId){
				shopStore.setQrShop('')
				fn && fn(obj);
			}
			console.log('查询此门店失败', err);
		});
}
export function handlerShopInfo(data:any, obj:any = {}, fn:any) {
	console.log("main_promote我们开始执行showShopInfo start")
	// global.IS_FIRST = false;
	// uni.setStorageSync(global.IS_FIRST_QueryMemberList, false)
	let array = [];
	for (let key in data) {
		// console.log('0000', key, data[key]);
		let item = data[key]
		let dist = key.split('.')[0];
		item['distanceUnit'] = dist.length > 3 ? '千米' : '米';
		dist = dist.length > 3 ? (Number(dist) / 1000).toFixed(2) : dist;
		item['distance'] = dist;
		array.push(item);
		break;
		// if (item.ext && item.ext.isSubscribe) {}

	}
	let shopData = array[0] || {};
	// if (uni.getSystemInfoSync().platform == 'devtools') { //开发者工具强制隆平店，方便调试 && env.envIndex == 2
	// 	shopData.nmember_id = 90455; //暂固定16681
	// }
	shopStore.setShop(shopData)
	// shopStore.commit('common/SET_SHOP_DATA', shopData)
	// 保存定位最近卖家-暂++
	// if (obj.isGPS) {
	// 	console.log('SET_NEAR_SHOP+++', shopData)
	// 	shopStore.commit('common/SET_NEAR_SHOP', shopData)
	// 	uni.setStorageSync(global.NEAR_SHOP, shopData);
	// }
	userStore.setChangeAdress(false);
	shopStore.setQrShop('');
	shopStore.setShop(shopData);
	obj.sellerMemberId = shopData.nmember_id || '1';
	fn && fn(obj);
}
export default {
	takeSaveShare,
	initShop,
	getSellerConfig,
	takeUserInfo
}